package com.mutouren.modules.organize.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.mutouren.common.orm.HibernateHelper;
import com.mutouren.common.orm.HibernateParamer;
import com.mutouren.common.orm.HibernateTrans;
import com.mutouren.common.orm.Transcation;
import com.mutouren.modules.organize.dao.UserRoleDao;
import com.mutouren.modules.organize.model.Function;
import com.mutouren.modules.organize.model.Role;
import com.mutouren.modules.organize.model.UserRole;

public class UserRoleDaoImpl implements UserRoleDao {

	@Override
	public void save(UserRole userRole, Transcation trans) {
		HibernateHelper.save(userRole, (HibernateTrans)trans);
	}

	@Override
	public void deleteByUserId(int userId, Transcation trans) {
		String sql = "delete UserRole a where a.userId = :userId ";

		List<HibernateParamer> listParam = new ArrayList<HibernateParamer>();
		listParam.add(new HibernateParamer("userId", userId));

		HibernateHelper.bulkUpdate(sql, listParam, (HibernateTrans)trans);		
	}

	@Override
	public List<Role> getRolesByUserId(int userId) {
		String sql = "select b.* from Org_UserRole a inner join Org_Role b where a.roleId = b.id and a.userId = :userId ";

		List<HibernateParamer> listParam = new ArrayList<HibernateParamer>();
		listParam.add(new HibernateParamer("userId", userId));

		return HibernateHelper.selectByNativeSql(Role.class, sql, listParam);				
	}

	@Override
	public List<Function> getFunctionsByUserId(int userId) {
		String sql = "select distinct d.* from Org_User a "
			+ "inner join Org_UserRole b on a.id=b.UserID "
			+ "inner join Org_Role e on b.RoleID = e.id "	
			+ "inner join Org_RoleFunction c on b.RoleID=c.RoleID "
			+ "inner join Org_function d on c.FuncId = d.id "
			+ "where a.id = :userId and e.validState=0";

		List<HibernateParamer> listParam = new ArrayList<HibernateParamer>();
		listParam.add(new HibernateParamer("userId", userId));

		return HibernateHelper.selectByNativeSql(Function.class, sql, listParam);
	}

}
